--[[
手游大厅界面
2015_12_03 C.P
]]

local ClientScene = class("ClientScene", cc.load("mvc").ViewBase)
local QueryExit = appdf.req(appdf.CLIENT_SRC.."app.views.layer.other.QueryDialog")
local PopWait = appdf.req(appdf.CLIENT_SRC.."app.views.layer.other.PopWait")
-- local GameListView	= appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.plaza.GameListLayer")
local protocol = require(appdf.CLIENT_SRC.."gamemodel.protocol")
local FreeGoldLayer = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.plaza.FreeGoldLayer")
local UserInfo = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.plaza.UserInfoLayer")
local Bank = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.plaza.BankLayer")
local Agents = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.plaza.AgentsLayer")
local KeFuLayer = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.plaza.KeFuLayer")
local RoomList = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.plaza.RoomListLayer")
local Shop = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.plaza.ShopLayer")
local Binding = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.plaza.BindingLayer")

local NoticeLayer = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.plaza.NoticeLayer")
local LogonFrame = appdf.req(appdf.CLIENT_SRC.."plaza.models.LogonFrame")
local GameFrameEngine = appdf.req(appdf.CLIENT_SRC.."plaza.models.GameFrameEngine")
local Room = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.room.RoomLayer")
local ExchangeLayerNew = appdf.req(appdf.CLIENT_SRC .. "plaza.views.layer.plaza.ExchangeLayer")
local HeadSprite = appdf.req(appdf.EXTERNAL_SRC .. "HeadSprite")
local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. "ExternalFun")
local ClipText = appdf.req(appdf.EXTERNAL_SRC .. "ClipText")
local MultiPlatform = appdf.req(appdf.EXTERNAL_SRC .. "MultiPlatform")
local utils = appdf.req(appdf.EXTERNAL_SRC .. "Utils")
local RichLabel = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.other.RichLabel")
local Broadcast = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.plaza.BroadcastLayer")
local loadingLayer = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.plaza.LoadingLayer")
local defaultMsgStr = "温馨提示：亲爱的玩家，充值成功后请到游戏银行查收领取金币，支付宝提现需要绑定您实名认证账号，祝你游戏愉快。"
ClientScene.BT_EXIT 		= 1 
ClientScene.BT_RECHARGE		= 4
ClientScene.BT_BANK			= 9
ClientScene.BT_EXCHANGE		= 15
ClientScene.BT_TRUMPET		= 18
ClientScene.BT_PERSON		= 19
ClientScene.BT_KEFU 	= 21
ClientScene.BT_NOTIC   = 23 --顶部公告按钮
ClientScene.BT_RELIEF   = 24 --顶部救济金按钮
ClientScene.BT_REGISTER = 25 --底部注册送金
ClientScene.BT_Kefu_Bubble = 26
ClientScene.BT_Mail_Bubble = 27
ClientScene.BT_TUIG 	= 28
ClientScene.BT_bindIntru = 29
ClientScene.BT_bindIntru_ok = 30
local BtnmoveX = 330  --收益按钮左移动的距离
-- 进入场景而且过渡动画结束时候触发。
function ClientScene:onEnterTransitionFinish()

	ExternalFun.playPlazzBackgroudAudio( )
	self.retryTime = 0
	self.bInEnter =  true
	self.ShowAgentTime = 1--连续只展示代理次数
	self.lastPayTime = 0   --上次支付成功的次数
	cc.SimpleAudioEngine:getInstance():resumeMusic()
	
	--根据会员等级确定裁剪资源
	local vipIdx = GlobalUserItem.cbMemberOrder or 0
	self._AreaTop:setPosition(cc.p(0,CC_DESIGN_RESOLUTION.height) )
	--裁切头像
	local head = HeadSprite:create(1,GlobalUserItem, 110,"plaza/head_mask3.png")
	if nil ~= head then
		head:setPosition(cc.p(50,50))
		self._btPersonInfo:addChild(head)
		self._head = head
		local frameFile = nil
		local scaleRate = nil
		frameFile = "plaza/headfram.png"
		scaleRate = 0.75
		self._head:enableHeadFrame(true, {_framefile = frameFile, _scaleRate = scaleRate,_posPer = cc.p(0.5,0.5)})
	end

	self:refreshLayer()
	self.scheduleTs = 1
	schedule(self,function( ... )
		-- body
		self.scheduleTs = self.scheduleTs + 1
		if self.scheduleTs%600 == 0 then    --马灯公告，客户端 10分钟1次
			self._LogonFrame:sendSocketData(protocol.CTRL_CLIENT_HALL,protocol.CXM_SCROLLNOTICE) 
		end
	end,1)
	self:initAngets()
	return self
end
function ClientScene:getChannelType( ... )
	return self.ChannelType
end
function ClientScene:initAngets( ... )
	self.btn_bindIntrod:setVisible(false)
	self.ChannelType = self:getApp()._serverConfig.ChannelType  --渠道类别(1=无代理正常渠道，2=代理渠道，3=全民渠道)
	self.Is_ChannelForce = self:getApp()._serverConfig.Is_ChannelForce  --1  强制绑定  0 不必强制
--is_qmagent  全民代理是否有下级代理  is_moreagent 是否绑定过多级代理   is_extension是否绑定过代理 
	self.rtuig_btn:setVisible(not GlobalUserItem.onlyShowLand and not GlobalUserItem.safeChannle )
	utils.getAgentsInfo( jsontab,function (data)
		local is_extension = data.is_extension
		self.is_qmagent = data.is_qmagent
		if data.is_openqm  == 1 then --is_openqm  is_extension ~= 1 and self.ChannelType == 3 and data.is_qmagent == 0 
			self:openAgents()
			--self.ChannelType == 2 and (not data.is_moreagent or data.is_moreagent == 0) and data.is_qmagent == 0 and is_extension ~= 1  
	elseif data.is_opendj == 1 then --is_moreagent 是否绑定多级代理 is_opendj
			local today = os.date("%d", os.time())
			today = tonumber(today)
			local lastopenIntrodutday = cc.UserDefault:getInstance():getIntegerForKey("openIntrodutday",0)
			if today ~= lastopenIntrodutday then
				self:openBindIntroduct()
				cc.UserDefault:getInstance():setIntegerForKey("openIntrodutday",today)
			end
			self.btn_bindIntrod:setVisible(true)
		elseif self.ChannelType == 2 and (data.is_moreagent == 1 or data.is_qmagent == 1)  then
			if self.btn_bindIntrod then
				self.btn_bindIntrod:removeFromParent()
			end
			
		end
	end)

end
--获取服务器config
function ClientScene:getserverConfig( ... )
	return self:getApp()._serverConfig
end
--获取渠道类型
function ClientScene:getAngetType( ... )
	return self.ChannelType
end

--查看是否有新的消息
function ClientScene:getSocketNewMassge()
	local today = os.date("%d", os.time())
	today = tonumber(today)
	local kefu_lastBubbleday = cc.UserDefault:getInstance():getIntegerForKey("kefuBubbleDay",0)
	local mail_lastBubbleday = cc.UserDefault:getInstance():getIntegerForKey("mailBubbleDay",0)
	self.isFirstGetKefuMassge = today ~= kefu_lastBubbleday
	self.isFirstGetMailMassge = today ~= mail_lastBubbleday
	self._LogonFrame:sendKefuMsg(cc.UserDefault:getInstance():getIntegerForKey("kefuMaxIdx", 0))
	self._LogonFrame:sendGetMyMail(cc.UserDefault:getInstance():getIntegerForKey("mymailMaxIdx", 0))
end

-- 退出场景而且开始过渡动画时候触发。
function ClientScene:onExitTransitionStart()
	self._sceneLayer:unregisterScriptKeypadHandler()
	return self
end

function ClientScene:onExit()
	if appdf.reloadclient then
		return
	end
	appdf.removeListener(self.customlistenerList)
	self:releasePublicRes()
	return self
end
--记录最近的奖池金额  
function ClientScene:getJackPotNum()
	return self.lastJackpot or 0
end
--socket回调
function ClientScene:onClientCallBack(wMsgID,pData)
	print("onClinetCallBack>>>>",wMsgID)
	--大厅奖池消息
	if wMsgID == protocol.SM_JACKPOTDATA then
		for k,v in pairs(pData.gamels) do
			if v.gameid == yl.fruitslot then
				self.lastJackpot = v.jackpot
			end
		end
		appdf.PostCustomEvent(yl.EVENT_JACKPORT_UPDATE,pData,self)
	elseif wMsgID == protocol.SM_PLAYERINFOEX  and not pData.subid  then
		GlobalUserItem.TodayAlmsCount = pData.todayalmscount or 2  --今天领取了多少次
		self:updateInfomation()

	elseif wMsgID == protocol.SM_SELECTGAME_ACK then
		--showToast(self,pData.msg or "",1)
		print("SM_SELECTGAME_ACK>>>>",pData.result)
		self:dismissPopWait()
		if pData.result ~=  1 then
		--	appdf.clientSocket:logout()
		--	appdf.clientSocket:onCloseSocket()
			self.queryLayer=QueryExit:create(pData.msg or "错误提示1", function (bReTry)
			--	os.exit(0)
			end)
			:setCanTouchOutside(false)
			:addTo(self,yl.MAX_INT)
			return
		end
		local tag = self._sceneRecord[#self._sceneRecord]
		if tag == yl.SCENE_GAME  then
			local entergame = self:getEnterGameInfo()
			if entergame and entergame.gameid then
				self:onSendEnterGame(true)
				-- self:onStartGame()
			else
				self:onChangeShowMode(yl.SCENE_GAMELIST)
			end
		end 
		self:dismissPopWait()
	elseif wMsgID == protocol.SM_LOGIN_ACK then
		self:dismissPopWait()
		if pData.result == 1 then
			local tag = self._sceneRecord[#self._sceneRecord]
			if tag == yl.SCENE_GAME or tag == yl.SCENE_ROOM  then
				local entergame = self:getEnterGameInfo()
				if entergame and entergame.gameid then
					self._gameFrame:onSelectGame(entergame.gameid)
				elseif  self.curgameid then
					self._gameFrame:onSelectGame(self.curgameid)
				else
					self:onChangeShowMode(yl.SCENE_ROOMLIST)
				end
			else
				-- self:onChangeShowMode(yl.SCENE_ROOMLIST)
			end 
		elseif pData.result < 0 then
			appdf.clientSocket:onCloseSocket()
			self.queryLayer=QueryExit:create(pData.msg or "错误提示1", function (bReTry)
				appdf.clientSocket:logout()
				self:ExitClient()
			end)
			:setCanTouchOutside(false)
			:addTo(self,yl.MAX_INT)
		end
	
	elseif wMsgID == protocol.SM_GAMECONTINUE or wMsgID == protocol.SM_CURGAME then
		local tag = self._sceneRecord[#self._sceneRecord]

		self:dismissPopWait()
		if tag == yl.SCENE_GAME  then
			self._LogonFrame:sendContinueGame(pData)
			return
		end 
		local entergame = self:getEnterGameInfo()
		dump(entergame,"SM_GAMECONTINUE")

	

		if (not pData.gameid or pData.gameid == 0  or 
		(entergame and pData.gameid == entergame.gameid and pData.roomid == entergame.roomid )) and  not self.bJustLoginIn then
			self:onEnterGameScene(nil,pData.gameid and pData.gameid~=0)
			return
		end
		self.bJustLoginIn =  false
		if not pData.gameid or pData.gameid < 1 then
			return
		end
		-- self:dismissPopWait()
		self.queryLayer=QueryExit:create(pData.msg or "您正在"..pData.name.."游戏中,点确定继续游戏", function (bReTry)
			if bReTry == true then
				if self._sceneLayer:getChildByTag(yl.SCENE_GAME) then
					return
				end 
				
				if yl.updateList[pData.gameid] and yl.updateList[pData.gameid] ~= 0 then
					showToast(self,"游戏正在更新",1)
					self:onKeyBack()
					return
				end
				self.gameInfo  = GlobalUserItem.roomwithGameidlist[pData.gameid]
				self.gameInfo.tableid = pData.tableid
				local version = tonumber(self:getApp():getVersionMgr():getResVersion(self.gameInfo.gameid))
				local path = appdf.gamepath..self.gameInfo.gameid
				local active =  not cc.FileUtils:getInstance():isDirectoryExist(path)
				
				self.game_ver_list = self:getApp()._serverConfig.game_ver_list or {}
				local verinfo = string.split(self.game_ver_list[tostring(self.gameInfo.gameid)] or "","_") or {}
				local _severcfg_zipver = trim(verinfo[1] or "0")   --最新版本

				if  (not version or tonumber(_severcfg_zipver) > version or active)  and  appdf.isDebug == 0 and not appdf.APPSTORE_VERSION 
				     then --
					local tag = self._sceneRecord[#self._sceneRecord]
					showToast(self,"游戏需要更新，请稍侯")
					if tag == yl.SCENE_GAME  then
						self:onKeyBack()
					else
						local roombtn = self.dst_layer.roomBtn[self.gameInfo.gameid]
						self.dst_layer:btnTouched(self.gameInfo,roombtn)
					end 
					return 
				end


				self:reSetGameSearchPath(pData.gameid)
				self:addGameSearchpath(pData.gameid)
				local roomls = self.gameInfo.roomls
				if roomls then
					for i,v in pairs(roomls) do
						if v.roomid == pData.roomid then
							self.gameInfo.roomid = v.roomid
							self.gameInfo.basescore = v.basescore
							self.gameInfo.enterlimit = v.enterlimit
							self.gameInfo.status = v.status

						end
					end
				end
				self:showPopWait(nil,self.curgameid )
				self:updateEnterGameInfo(self.gameInfo )
				self:onEnterGameScene(function( ... )
					self.gameInfo.nEnterRoomIndex = GlobalUserItem.nCurRoomIndex
					self._gameFrame:onInitData()
					self._gameFrame:setKindInfo(GlobalUserItem.nCurGameKind, GlobalUserItem.selectGameVersion)
					-- body
					self._LogonFrame:sendContinueGame(pData)
				end,true)
				
			end
		end)
		:setCanTouchOutside(false)
		:addTo(self)
		
	elseif wMsgID == protocol.SM_GAMELIST then
		if not yl.needRefreshGameList  then
			return
		end
		local tag = self._sceneRecord[#self._sceneRecord]
		ExternalFun.httpNewVersion(self)
		if tag == yl.SCENE_ROOMLIST  then
			if self.dst_layer and self.dst_layer.initView then
				performWithDelay(self,function( ... )
					-- 有在更新返回
					for i,v in pairs(yl.updateList) do  
						if v and v ~= 0 then
							return
						end
					end
					if self.dst_layer and self.dst_layer.initView then
						self.dst_layer:initView(true)
					end
				end,3)
			end
		end
	
	elseif wMsgID == protocol.SM_ENTERROOM_ACK then

		if pData.result ~= 1 then
			-- showToast(self,"进入游戏失败",1)
			local tag = self._sceneRecord[#self._sceneRecord]
			if tag == yl.SCENE_GAME  then
				self:onKeyBack()
			end 
			if pData.result == -3 then
				local gamename = yl.GAME_NOTICE_TYPE[pData.gameid] or ""
				local limitmoney = 0
				for k,v in pairs(GlobalUserItem.roomwithGameidlist[pData.gameid].roomls) do
					if pData.roomid and v.roomid == pData.roomid then
						limitmoney = v.enterlimit/appdf.bili
					end
				end
				self.queryLayer=QueryExit:create("当前房间进入需要"..limitmoney..yl.UNIT.."，您金币不足，请充值？", function (bReTry)
					if bReTry == true then
					self:onChangeShowMode(yl.SCENE_SHOP)
						
					end
				end,true)
				:setCanTouchOutside(false)
				:addTo(self,yl.MAX_INT)
				return
			elseif pData.result == -9 then  -- 结算异常
				self.queryLayer=QueryExit:create(pData.msg or "进入游戏失败.", function (bReTry)
					local tag = self._sceneRecord[#self._sceneRecord]
					if tag == yl.SCENE_GAME then
						self:onKeyBack()
					end
				end)
				:setCanTouchOutside(false)
				:addTo(self,yl.MAX_INT)
				return
			else
				self.queryLayer=QueryExit:create(pData.msg or "进入游戏失败.", function (bReTry)
					local tag = self._sceneRecord[#self._sceneRecord]
					if tag == yl.SCENE_GAME then
						self:onKeyBack()
					else
						self:dismissPopWait()
					end
				end)
				:setCanTouchOutside(false)
				:addTo(self,yl.MAX_INT)
				return
				-- showToast(self,(pData.msg or ""),2)
			end
			return
		end	
		if  ExternalFun.enterGameAction( self.curgameid ) then -- yl.GAME_TYPE_BAIREN self.curgameid ~= 107
			self:dismissPopWait()
		end
	elseif wMsgID == protocol.SM_DELTABLE then
		

	elseif wMsgID == protocol.SM_GAME_MESSAGE then
		if pData.subid == 100 and not pData.roomid then
			
		end
		
	elseif wMsgID == protocol.SXM_VERIFYCODE then   --发送注册验证码回调
		showToast(self,pData.msg or "发送失败",1)
	elseif wMsgID == protocol.SXM_REGISTER then   --发送注册请求后的回调
		local _Layer = self:getChildByTag(yl.SCENE_BINDING)
		local _Layer2 = self:getChildByTag(yl.SCENE_NOTICE)
		local userlayer = self._sceneLayer:getChildByTag(yl.SCENE_USERINFO)
		if _Layer2 then
			_Layer2:bindcb(pData)
		end
		if _Layer then
			_Layer:bindcb(pData)
		end
		if userlayer then
			userlayer:refreshLayer()
		end
		self:refreshLayer()
		
	elseif wMsgID == protocol.SXM_FEEDBACK then   --发送客服消息后的回调
		local _KeFuLayLayer = self._sceneLayer:getChildByTag(yl.SCENE_KEFU)
		
		if pData.result == 1 then
			_KeFuLayLayer:sendfeedBackSuccess()
			self._LogonFrame:sendKefuMsg(cc.UserDefault:getInstance():getIntegerForKey("kefuMaxIdx", 0))
		else 
			showToast(self,"发送失败请重试",2)
		end
		
		--_KeFuLayLayer.Tokefu_editbox:setText("")
	elseif wMsgID == protocol.SXM_REPLY  then   --获取客服消息
	
		local _KeFuLayLayer = self._sceneLayer:getChildByTag(yl.SCENE_KEFU)
		if _KeFuLayLayer then
			--更新客服lishiview
			_KeFuLayLayer:updataChatListview(pData)
		elseif pData.result and  pData.result > 0 then
			self.kefuRedPointSp:setVisible(true)
			self.kefu_bubble:setVisible(self.isFirstGetKefuMassge and not GlobalUserItem.safeChannle)
		end
		self.isFirstGetKefuMassge = false
	elseif wMsgID == protocol.SXM_GETMAIL then   --获取邮件
		
		local _noticeLayer = self._sceneLayer:getChildByTag(yl.SCENE_GAMENOTICE)
		if _noticeLayer then
			_noticeLayer:updataMyMailTable(pData)
			_noticeLayer:loadMail()
		elseif pData.result and  pData.result > 0 then
			self.msgRedPointSp:setVisible(true)
			
		end
		if self.msgRedPointSp:isVisible() and self.isFirstGetMailMassge then
			self.mail_bubble:setVisible(true)
		else
			self.mail_bubble:setVisible(false)
		end
		self.isFirstGetMailMassge = false
	elseif wMsgID == protocol.SXM_GETNOTICE then   --获取游戏公告
		local _noticeLayer = self._sceneLayer:getChildByTag(yl.SCENE_GAMENOTICE)
		if _noticeLayer  then
			_noticeLayer:updataNoticeMailTable(pData)
			_noticeLayer:refrashNoticeListview()
		elseif pData and pData.result>0 then
			for k,v in ipairs(pData.list) do
				if v.pop == 1 then
					self:openPopLayer(v.content)
				end
			end
		end
		
	elseif wMsgID == protocol.SXM_INSUREGOLD_DEC then   --保险箱取出
		local _bankLayer = self._sceneLayer:getChildByTag(yl.SCENE_BANK)
		if _bankLayer then
			_bankLayer:onTakeCallBack(pData)
		end
	elseif wMsgID == protocol.SXM_INSUREGOLD_INC then   --保险箱存入
		local _bankLayer = self._sceneLayer:getChildByTag(yl.SCENE_BANK)
		if _bankLayer then
			_bankLayer:onSaveCallBack(pData)
		end
	elseif wMsgID == protocol.SXM_GETALMS then   --救济金（回应）
	    self:dismissPopWait()
		if pData.result == 1 then
			GlobalUserItem.TodayAlmsCount = pData.todayalmscount
			local tbArmaturename ={"Armature/CZDZ/CZDZ.ExportJson"}
			ExternalFun.addArmatureCacheAsync(tbArmaturename,function( ... )

				utils.showArrivalLayer(GlobalUserItem.channelconfig.almscount/appdf.bili)
			end)
			local today = os.date("%d", os.time())
			cc.UserDefault:getInstance():setStringForKey("freegoldDay",today)
			local _Layer = self:getChildByName("freegold")
		end
		self:removeChildByName("freegold")
	--	showToast(self,pData.msg or "领取失败",2)
	elseif wMsgID == protocol.SXM_EXCHANGESETTING then --兑换配置
		showToast(self,pData.msg or "",2)
		exchangeConfig= pData
	
		GlobalUserItem.exchangeConfig = exchangeConfig
	
	elseif wMsgID == protocol.SM_CHANNELCONFIG then --渠道配置  是否显示游戏公告(SM_GAMENOTICE,)、体现是否需要验证码
		GlobalUserItem.channelconfig = pData   --exchangesms     gamenotice  alimslimit=救济金条件 almsnum=救济金次数   almscount= 救济金数量  reggold=注册送的金额
		local _Layer = self:getChildByTag(yl.SCENE_NOTICE)
		if _Layer then
			_Layer:setreggold()
		end
	elseif wMsgID == protocol.SXM_PLAT  then --平台配置 
		if pData and  pData.list then
			GlobalUserItem.URLconfig = pData.list[1]
			if not appdf.isNullString( GlobalUserItem.URLconfig.exchangemethodurl) then
				utils.getExchangeInfo({},function (recdata)
						GlobalUserItem.ExchangeInfo = recdata
				end)
			end			
		end		
	elseif wMsgID == protocol.SXM_SCROLLNOTICE then   --获取滚动公告
		if GlobalUserItem.onlyShowLand then
			return
		end
		yl.brocastData =  nil
		local list = pData.list or {}
	--	self.broadcast:setNoticeData(list)
		local _Layer = self._sceneLayer:getChildByTag(yl.SCENE_GAME)
		if _Layer and self.gamebroadcast then
			self.gamebroadcast:setNoticeData(list)
		elseif self.broadcast then
			self.broadcast:setNoticeData(list)
		end
	elseif wMsgID == protocol.SM_GAMENOTICE then   --获取游戏滚动公告
		if GlobalUserItem.onlyShowLand then
			return
		end
		if  ( GlobalUserItem.channelconfig and GlobalUserItem.channelconfig.gamenotice == 1 
		and pData.msg and type(pData.msg) == "string" ) then
			local _Layer = self._sceneLayer:getChildByTag(yl.SCENE_GAME)
			local noticedata = cjson.decode(pData.msg)
			if noticedata.game_id == yl.fruitslot then
					appdf.PostCustomEvent(yl.EVENT_JACKPORT_BIGPRECE,pData,self)
			end
			if not tolua.isnull(self.gamebroadcast) then
				if _Layer and self.gamebroadcast then
					self.gamebroadcast:setGameNoticeData(noticedata)
				end
			else
				self.broadcast:setGameNoticeData(noticedata)
			end
			if noticedata.gold < 10000 then
				self.queryLayer=QueryExit:create(pData.msg, function (bReTry)
					
				end)
				:setCanTouchOutside(false)
				:addTo(self)
			end
			
		else
			self.broadcast:removeGamenotice()
		end 

	elseif wMsgID == protocol.SXM_QUESTDATA then

	
	elseif wMsgID == protocol.SM_NOTIFY then
	
		if pData.notify == protocol.NOTIFYID_LOGOUT then
			
			appdf.clientSocket:onCloseSocket()
			self._LogonFrame:closeHeartBreak()
			self.queryLayer=QueryExit:create(pData.msg or "错误提示1", function (bReTry)
			self:ExitClient()
			end)
			:setCanTouchOutside(false)
			:addTo(self,yl.MAX_INT)
		elseif pData.notify == protocol.NOTIFYID_BACKHALL  then
			local tag = self._sceneRecord[#self._sceneRecord]
			if tag == yl.SCENE_GAME then
				appdf.clientSocket:onCloseSocket()
				self.queryLayer=QueryExit:create(pData.msg or "错误提示2", function (bReTry)
					self:onKeyBack()
				end)
				:setCanTouchOutside(false)
				:addTo(self)
			end
		elseif pData.notify == protocol.NOTIFYID_NEWREPLY  then --web新的客服回复消息
			local _KeFuLayLayer = self._sceneLayer:getChildByTag(yl.SCENE_KEFU)
			if _KeFuLayLayer then
				self._LogonFrame:sendKefuMsg(cc.UserDefault:getInstance():getIntegerForKey("kefuMaxIdx", 0))
				
			end
			self.kefuRedPointSp:setVisible(true)
		elseif pData.notify ==  protocol.NOTIFYID_RECHARGE  then --充值到帐通知
			if self.isgetYongjin then
				self.isgetYongjin = false
				return
			end
			local money = ExternalFun.ChangeScore(pData.value,2,",")
			utils.showArrivalLayer(money)
			
			local hasRechargeCount = cc.UserDefault:getInstance():getIntegerForKey("hasRechargeCount",0)
			hasRechargeCount = hasRechargeCount + money
			cc.UserDefault:getInstance():setIntegerForKey("hasRechargeCount",hasRechargeCount)
			self:RefreshmoveBottomBtn()

			self:dismissPopWait()
		elseif pData.notify ==  protocol.NOTIFYID_NEWMAIL  then -- 收到新的邮件

			self.msgRedPointSp:setVisible(true)
		end
	elseif wMsgID == protocol.SXM_EXCHANGE then	--兑换
		appdf.PostCustomEvent("EXCHANGE",pData,self)
	elseif wMsgID == protocol.SXM_EXCHANGERECORD then	--兑换记录
		appdf.PostCustomEvent("exchangeRecords",pData,self)
	elseif wMsgID == protocol.SXM_CHANGEFACE then  --修改头像
		appdf.PostCustomEvent("CHANGEFACE",pData,self)
	elseif wMsgID == protocol.SXM_CHANGENICK then --修改昵称
		appdf.PostCustomEvent("CHANGENICK",pData,self)
	elseif wMsgID == protocol.SXM_SETBANKID then --绑定银行
		appdf.PostCustomEvent("SETBANKID",pData,self)
	elseif wMsgID == protocol.SXM_SETALIPAYID then --绑定支付宝
		appdf.PostCustomEvent("SETALIPAYID",pData,self)
	
	elseif wMsgID == protocol.SM_TABLE_LIST then --桌子数据SM_TABLE_LIST

		--dump(pData.tablels[1],"SM_TABLE_LIST")
		self.bjl_tablels_info = pData.tablels
		self.bjl_tablels_info_ts = os.time()
		print("bjl_tablels_info_ts1111>>>>",self.bjl_tablels_info_ts)
		if not self.curgameid then
			return
		end
		if  yl.GAME_TYPE_BAIREN[self.curgameid] then

			local roomList = self._sceneLayer:getChildByTag(yl.SCENE_ROOM)
			if roomList  then
				roomList:refreshListView(pData.tablels)
			end	
		end
		
	elseif wMsgID == protocol.SM_TABLE_STATUS then --桌子数据SM_TABLE_STATUS
		self.bjl_tablels_info_ts = os.time()
		print("bjl_tablels_info_ts2222>>>>",self.bjl_tablels_info_ts)
		local roomList = self._sceneLayer:getChildByTag(yl.SCENE_ROOM)
		if not self.gameInfo or not (roomList and (self._sceneRecord[#self._sceneRecord] == yl.SCENE_ROOM ) )  then
			return
		end
		if self.gameInfo.gameid == yl.baccaratnew or self.gameInfo.gameid == yl.baccaratnew_video then
			
			if pData.data.draw_result then
				roomList:addLudan( pData)
			elseif pData.data.status ~= -1 then
				roomList:changeStatus(pData)
			elseif pData.data.status == -1 then
				roomList:clearLudan( pData)
			end
	
		elseif self.gameInfo.gameid == yl.balckred then

			if pData.data.draw_result then
				roomList:addLudan( pData)
			else
				roomList:changeStatus(pData)

			end
		elseif self.gameInfo.gameid == yl.longhudou then

			if pData.data.draw_result then
				roomList:addLudan( pData)
			elseif pData.data.status ~= -1 then
				roomList:changeStatus(pData)
			elseif pData.data.status == -1 then
				roomList:clearLudan( pData)
			end
		elseif self.gameInfo.gameid == yl.oxbattle then

			if pData.data.draw_result then
				roomList:addLudan( pData)
			else
				roomList:changeStatus(pData)

			end
		elseif self.gameInfo.gameid == yl.sharkbattle then

			if pData.data.draw_result then
				roomList:addLudan( pData)
			elseif pData.data.status ~= -1 then
				roomList:changeStatus(pData)
			end
		elseif self.gameInfo.gameid == yl.bcbm then

			if pData.data.draw_result then
				roomList:addLudan( pData)
			elseif pData.data.status ~= -1 then
				roomList:changeStatus(pData)
			end
		end

		
	--	dump(pData.data,"SM_TABLE_STATUS")
	elseif wMsgID == protocol.SM_TABLE_DELETE then --桌子数据SM_TABLE_DELETE
		if self.gameInfo.gameid ~= yl.baccaratnew then
			return
		end
	elseif wMsgID == protocol.SM_TABLE_CLEAR then --桌子数据SM_TABLE_CLEAR
		if self.gameInfo.gameid ~= yl.baccaratnew and self.gameInfo.gameid ~= yl.baccaratnew_video and self.gameInfo.gameid ~= yl.balckred then
			return
		end
		local bjlroomList = self._sceneLayer:getChildByTag(yl.SCENE_ROOM)
		if bjlroomList  then
			bjlroomList:clearlistview()
		end
	--	dump(pData.data,"SM_TABLE_CLEAR")
	elseif wMsgID < 0 then
		self:dismissPopWait()
		message = pData or "网络连接失败"
		if type(message) == "string" and message ~= "" then
			showToast(self._topLayer,message,1,cc.c4b(250,0,0,255));
		end
		if self.queryLayer and not tolua.isnull(self.queryLayer) then
			return
		end
		self.queryLayer=QueryExit:create(message, function (bReTry)
			if bReTry == true then
				ExternalFun.httpNewVersion(self)
				appdf.clientSocket:connectServer()
			else
				os.exit(0)
			end
		end)
		:setCanTouchOutside(false)
		:addTo(self,yl.MAX_INT)
	end
end
function ClientScene:setLabaVisible(bvisib)
	local layer =  self._sceneLayer:getChildByTag(yl.SCENE_ROOMLIST)
	local layer2 =  self._sceneLayer:getChildByTag(yl.SCENE_ROOM)
	if layer or layer2 then
		self._notify:setVisible(true and (not GlobalUserItem.onlyShowLand and not GlobalUserItem.safeChannle) )
	else
		self._notify:setVisible(bvisib or false)
	end
	
end

function ClientScene:openFreeGoldLayer()

		local layer =  FreeGoldLayer:create(self)
		layer:setName("freegold")
		self:addChild(layer,5)
end
function ClientScene:openPopLayer(str)
	if device.platform == "windows" then
		return
	end
	local popnode = ExternalFun.loadCSB("plaza/poplayer.csb", self )
	popnode:getChildByName("Text_1"):setString(str)
	popnode:getChildByName("closebt"):addTouchEventListener(function(ref,type) 
		if type == ccui.TouchEventType.ended then
			
			popnode:removeFromParent()
		end
		end)
end
function ClientScene:initSocketEvent( ... )
	
	-- 大厅界面消息回调   处理大厅界面
	local clientCallBack = function (result,message)
		-- print("ClientScene clientCallBack>>>>>>",result,message)
		if self.onClientCallBack then
			self:onClientCallBack(result,message)
		end
	end
	local _LogonFrame = LogonFrame:create(self,clientCallBack)
	self._LogonFrame = _LogonFrame
	--游戏界面消息回调  处理游戏界面
	local _gameFrame = GameFrameEngine:create(self, function (wMsgID,recvJson)
		print("ClientScene onGameCallBack>>>>>>",wMsgID)
		if self.onGameCallBack then
			self:onGameCallBack(wMsgID,recvJson)
		end
	end)
	self._gameFrame = _gameFrame

	appdf.clientSocket:setViewFrame(self)
	appdf.clientSocket:setCallBack(clientCallBack)
	appdf.clientSocket.onSocketClientEvent  =  function ( self,wMsgID,recvJson )
		--消息回调   处理数据
		_LogonFrame:onSocketEvent(wMsgID,recvJson)
		_gameFrame:onSocketEvent(wMsgID,recvJson)
	end
	appdf.clientSocket.onSocketLoginEvent  = nil  -- 去掉登录界面事件回调
end

-- 初始化界面
function ClientScene:onCreate()
	
	print("ClientScene onCreate >>>>>",appdf.padgameid )
	self.bJustLoginIn = true
	self:initView()
	appdf.inClientScene =  true
	self._gameFrame:onCheckCurGame()
	self:initCustomEventListener()
	ExternalFun.initExternalFun()
end

-- 初始化 自定义事件监听
function ClientScene:initCustomEventListener()
	local events = {yl.EVENT_LOAD_GAMERES_SUCCESS,yl.EVENT_LOAD_GAMERES_FAILED,yl.EVENT_REMOVE_GAME_LOADING}
	self.customlistenerList = appdf.initListener(events,function(evt)
		print("initCustomEventListener>>>>",evt.name)
		local data = evt.data
		if evt.name == yl.EVENT_LOAD_GAMERES_SUCCESS then
			-- self:dismissPopWait()
			-- self:stopAction(self.delayPopWait)
			if self.entergameCallback then
				self.entergameCallback()
			elseif self.onSendEnterGame then
				self:onSendEnterGame()  -- 游戏资源加载成功后 发送进入游戏请求
			end
		elseif evt.name == yl.EVENT_LOAD_GAMERES_FAILED then
			--游戏资源加载失败  返回上一级界面
			showToast(self,"游戏资源加载失败",1)
			if not self.dismissPopWait then
				return 
			end
			self:dismissPopWait()
			self:stopAction(self.delayPopWait)
			local curScene = self._sceneRecord[#self._sceneRecord]
			if curScene then
				if curScene == yl.SCENE_GAME then
					self:onKeyBack()
				end
			end
		elseif evt.name == yl.EVENT_REMOVE_GAME_LOADING then
			---清掉游戏加载loading 界面
			if not self.dismissPopWait then
				return 
			end
			self:dismissPopWait()
			self:stopAction(self.delayPopWait)
		end
	end,self)
end




-- 初始化界面
function ClientScene:initView()
	
	self.m_listener = nil
	self:cachePublicRes()
	self:initSocketEvent()
	GlobalUserItem.isBindphone =  appdf.bingPhone and appdf.bingPhone ~= ""
	
	self:getApp()._gameList = GlobalUserItem.roomkindlist
	local this = self
	--保存进入的游戏记录信息
	GlobalUserItem.m_tabEnterGame = nil
	--上一个场景
	self.m_nPreTag = nil
	--喇叭发送界面
	self.m_trumpetLayer = nil
--	local sdf = string.gsub("撒旦发dfsdf撒旦发撒旦发","w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*","") 
	-- 背景
	self._bg = ccui.ImageView:create("plaza/plazz/background.png")
	self._bg:setAnchorPoint(0,0)
	:move(0,0)
	:addTo(self)
	
	--提示文本
	self._txtTips = cc.Label:createWithTTF("", "fonts/round_body.ttf", 24)
	:setTextColor(cc.c4b(0,250,0,255))
	:setAnchorPoint(cc.p(1,0))
	-- :enableOutline(cc.c4b(0,0,0,255), 1)
	:move(appdf.WIDTH,0)
	:addTo(self,10)
	
	local btcallback = function (ref, type)
		if type == ccui.TouchEventType.ended then
			ref:setScale(1)
			this:onButtonClickedEvent(ref:getTag(),ref)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then
			ref:setScale(1)
	
		end
	end
	
	self._sceneRecord = {}
	self._gameSearPathList = {}
	self._sceneLayer = display.newLayer()
	:setContentSize(yl.WIDTH,yl.HEIGHT)
	:addTo(self)
	
	
	
	--返回键事件
	self._sceneLayer:registerScriptKeypadHandler(function (event)
		if event == "backClicked" then
			if self._popWait == nil then
				if #self._sceneRecord > 0 then
					local cur_layer =  this._sceneLayer:getChildByTag(self._sceneRecord[#self._sceneRecord])
					if cur_layer and cur_layer._queryDialog then
						cur_layer._queryDialog:removeSelf()
						cur_layer._queryDialog = nil
						return
					end
					if cur_layer  and cur_layer.onKeyBack then
						if cur_layer:onKeyBack() == true then
							return
						end
					end
				end
				self:onKeyBack()
			else
				self._popWait:removeSelf()
				self._popWait = nil
			end
		elseif event then
			-- self:onBackgroundCallBack(false)
		end
	end)
	self._sceneLayer:setKeyboardEnabled(true)
	
	--加载csb资源
	local rootLayer, csbNode = ExternalFun.loadRootCSB( "plaza/PlazzLayer.csb", self )

	self.m_plazaLayer = csbNode
	local layeraction = cc.CSLoader:createTimeline("plaza/PlazzLayer.csb")
	csbNode:runAction(layeraction)
	layeraction:gotoFrameAndPlay(0,60, true);
	--底部区域
	local areaBottom = csbNode:getChildByName("bottom_bg")
	self._AreaBottom = areaBottom
	
	
	
	--顶部区域
	local areaTop = csbNode:getChildByName("top_bg")
	self._AreaTop = areaTop
	-- ExternalFun.FixTopUI(areaTop)
	-- self._AreaTop:runAction(cc.MoveTo:create(0.2,cc.p(0,display.height)))
	
	self.btnlistview = areaBottom:getChildByName("btnListView")
	self.btcallback = btcallback
	--返回
	self._btExit = areaTop:getChildByName("btn_return")
	self._btExit:setVisible(false)
	self._btExit:setTag(ClientScene.BT_EXIT)
	self._btExit:addTouchEventListener(btcallback)
	self.gameNameSp = areaTop:getChildByName("gameNamesp")

	
	
	--查看信息
	self._btPersonInfo = areaTop:getChildByName("bt_person")
	self._btPersonInfo:setTag(ClientScene.BT_PERSON)
	self._btPersonInfo:addTouchEventListener(btcallback)
	
	--昵称
	self.nickNameText = areaTop:getChildByName("Text_6")

	
	--金币
	self._gold = areaTop:getChildByName("atlas_coin")
	
	--拷贝名称按钮
	local btn = areaTop:getChildByName("copyName_btn")
	btn:setTag(ClientScene.BT_PERSON)
	btn:addTouchEventListener(btcallback)
	
	
	btn = areaTop:getChildByName("uerinfobtn2")
	btn:setTag(ClientScene.BT_PERSON)
	btn:addTouchEventListener(btcallback)

	
	--救济金按钮
	btn = areaTop:getChildByName("relief_btn")
	btn:setTag(ClientScene.BT_RELIEF)
	btn:addTouchEventListener(btcallback)
	self.freemoney_text = btn:getChildByName("freemoney_text")
	self.freemoneybg = btn
	--顶部公告
	btn = areaTop:getChildByName("notic_btn")
	btn:setTag(ClientScene.BT_NOTIC)
	btn:addTouchEventListener(btcallback)
	self.noticeBtn=btn
	self.msgRedPointSp = btn:getChildByName("noticRedPoint")
	self.msgRedPointSp:setVisible(false)
	btn = btn:getChildByName("bubble") --气泡
	btn:setTag(ClientScene.BT_Mail_Bubble)
	btn:addTouchEventListener(btcallback)
	btn:setVisible(false)
	self.mail_bubble = btn
	--底部充值按钮
	btn = areaBottom:getChildByName("btn_CZ")
	btn:setTag(ClientScene.BT_EXCHANGE)
	btn:addTouchEventListener(btcallback)
	btn:setVisible(false)
	dh = btn:getChildByName("ArmatureNode_1")
	dh:setVisible(false)

	local cz_size = areaBottom:getContentSize()
	local btn_cz_new = ccui.Button:create("client/res/plaza/plazz/btn_chongzhi.png","client/res/plaza/plazz/btn_chongzhi.png")
	btn_cz_new:setTag(ClientScene.BT_EXCHANGE)
	btn_cz_new:move(cz_size.width-180 ,cz_size.height/2 )
	btn_cz_new:addTo(areaBottom)
	btn_cz_new:addTouchEventListener(btcallback)

--[[
	local particle = cc.ParticleSystemQuad:create("plaza/particle_texture.plist")
	btn:addChild(particle, 10)
	particle:setPosition(cc.p(250,52))
--]]
	self.needMoveBtn = {}
	--推广按钮
	self.rtuig_btn = areaTop:getChildByName("btn_tuig")
	self.rtuig_btn:setTag(ClientScene.BT_TUIG)
	self.rtuig_btn:addTouchEventListener(btcallback)   		-- 隐藏推广按钮 by djy
	-- self.rtuig_btn:runAction(
	-- 	cc.RepeatForever:create(cc.Sequence:create(
	-- 		cc.Blink:create(1,2),
	-- 		cc.MoveBy:create(1,cc.p(0,-100)),
	-- 		cc.MoveBy:create(1,cc.p(0,100))
	-- 	)))
	local size = self.rtuig_btn:getContentSize()
	local tuigSpine = sp.SkeletonAnimation:create("Armature/angent/quanming.json", "Armature/angent/quanming.atlas", 1)
	tuigSpine:setVisible(true);								-- 隐藏推广按钮 by djy
	tuigSpine:setPosition(size.width/2,size.height/2) 
	tuigSpine:addTo(self.rtuig_btn)
	tuigSpine:setAnimation(0, "animation", true)
	--底部注册送金按钮
	self.register_btn = self.btnlistview:getChildByName("btn_rigister")
	
	self.register_btn:setTag(ClientScene.BT_REGISTER)
	self.register_btn:addTouchEventListener(btcallback)
	if GlobalUserItem.accounttype == 1 then
		self.register_btn:removeFromParent()
	end
	
	local btnInfo = {}
	btnInfo.btn = self.btnlistview
	btnInfo.pos = cc.p(btnInfo.btn:getPositionX(),btnInfo.btn:getPositionY())
	table.insert(self.needMoveBtn,btnInfo)
	
	btn = self.btnlistview:getChildByName("btn_bindIntrod")
	btn:setTag(ClientScene.BT_bindIntru)
	btn:addTouchEventListener(btcallback)
	self.btn_bindIntrod = btn
	--顶部充值按钮
	btn = areaTop:getChildByName("btn_return_0")
	btn:setTag(ClientScene.BT_EXCHANGE)
	btn:addTouchEventListener(btcallback)

	btn = areaTop:getChildByName("paybtn2")
	btn:setTag(ClientScene.BT_EXCHANGE)
	btn:addTouchEventListener(btcallback)


	--客服
	btn = areaBottom:getChildByName("btn_kefu")
	
	local btnInfo = {}
	btnInfo.btn = btn
	btnInfo.pos = cc.p(btnInfo.btn:getPositionX(),btnInfo.btn:getPositionY())
	table.insert(self.needMoveBtn,btnInfo)
	
	btn:setTag(ClientScene.BT_KEFU)
	btn:addTouchEventListener(btcallback)
	self.kefuRedPointSp = btn:getChildByName("kefuRedPoint")
	self.kefuRedPointSp:setVisible(false)
	btn = btn:getChildByName("bubble") --气泡
	btn:setTag(ClientScene.BT_Kefu_Bubble)
	btn:addTouchEventListener(btcallback)
	btn:setVisible(false)
	self.kefu_bubble = btn
	
	performWithDelay(self,function ()
		self.kefu_bubble:setVisible(false)
		self.mail_bubble:setVisible(false)
		
	end,20)
	--保险箱
	btn = self.btnlistview:getChildByName("btn_take")
--[[	local btnInfo = {}
	btnInfo.btn = btn
	btnInfo.pos = cc.p(btnInfo.btn:getPositionX(),btnInfo.btn:getPositionY())
	table.insert(self.needMoveBtn,btnInfo)--]]
	btn:setTag(ClientScene.BT_BANK)
	btn:addTouchEventListener(btcallback)
	self.m_btnTask = btn
	
	
	
	--兑换
	self.recharge = areaBottom:getChildByName("btn_exchange")
	local btnInfo = {}
	btnInfo.btn = self.recharge
	btnInfo.pos = cc.p(btnInfo.btn:getPositionX(),btnInfo.btn:getPositionY())
	table.insert(self.needMoveBtn,btnInfo)
	self.recharge:setTag(ClientScene.BT_RECHARGE)
	self.recharge:addTouchEventListener(btcallback)
	self.recharge:setVisible(not appdf.APPSTORE_VERSION)

	
	--喇叭
	self._notify = areaTop:getChildByName("sp_trumpet_bg")
	ExternalFun.FixScaleUI(self._notify,false,false,4)
	-- self._notify:setPositionY(100)
	local thumpetSize = self._notify:getContentSize()
	btn = self._notify:getChildByName("btn_trumpet")
	btn:setTag(ClientScene.BT_TRUMPET)
	--btn:addTouchEventListener(btcallback)
	btn:setTouchEnabled(false)
	local trumpetPX, trumpetPY = btn:getPosition()
	local stencil  = display.newSprite()
	:setAnchorPoint(cc.p(0,0.5))
	stencil:setTextureRect(cc.rect(0,0,thumpetSize.width-210,thumpetSize.height))
	self._notifyClip = cc.ClippingNode:create(stencil)
	:setAnchorPoint(cc.p(0,0.5))
	self._notifyClip:setInverted(false)
	self._notifyClip:move(trumpetPX+10,trumpetPY)
	self._notifyClip:addTo(self._notify)
	self:setLabaVisible(true)
	
	self.broadcast = Broadcast:create(self,self._notify)	
	self.broadcast:addTo(self._notifyClip)
	

	self.m_tabInfoTips = {}
	self._tipIndex = 1
	self.m_nNotifyId = 0

	-- 公告是否运行
	self.m_bNotifyRunning = false
	self.gamebroadcast = nil
	self.m_bSingleGameMode = false
	
	
	local checkInInfo = function (result, msg, subMessage)
		local bRes = false
		showToast(self,msg or "更新数据失败",2)
		if not yl.checkuserinfo then
			yl.checkuserinfo =  true
		end
		
		
		return bRes
	end
	
	
	
	setbackgroundcallback(function (bEnter)
		if type(self.onBackgroundCallBack) == "function" then
			self:onBackgroundCallBack(bEnter)
		end
	end)
	

	--快速开始
	self.m_bQuickStart = false
	
	--游戏喇叭列表
	self.m_gameTrumpetList = {}
	
	-- 回退
	self.m_bEnableKeyBack = true
	
	-- 金币、金币动画
	
	
	if GlobalUserItem.accounttype == 0 and not appdf.APPSTORE_VERSION and not appdf.reloadclient then
			if device.platform ~= "windows" then
			--	self:openBindingLayer(yl.SCENE_NOTICE)
				appdf.reloadclient =  true
			end
			
	
	end
	
	local bfirstgame = cc.UserDefault:getInstance():getBoolForKey("firstGame",true)
	local lockcity = self:getApp()._serverConfig.lockcity -- 当前客户端所在城市
	self.firstEnterClientTime = os.time()
	
	
	if  (bfirstgame and lockcity) then 
		for k,v in ipairs(self.needMoveBtn) do
			v.btn:setPositionX(v.pos.x-BtnmoveX)
		end
		self:showPopWait()
		local dst = device.writablePath .. "download/"
		unZipAsync("100_base.zip",dst,function(result)
			print("onUnZipBase result client >>>>>",result)
			-- parent._txtTips:setString("解压文件，请稍候....")
			if checkint(result) == 1 then
				cc.UserDefault:getInstance():setBoolForKey("firstGame",false)
				self:dismissPopWait()
			
				self:RefreshmoveBottomBtn()	
				self:onChangeShowMode(yl.SCENE_ROOMLIST)
	
				self:CheckNotic()
				self:getSocketNewMassge()
				
			end		
		end)
	else
		cc.UserDefault:getInstance():setBoolForKey("firstGame",false)
		self:RefreshmoveBottomBtn()	
		self:onChangeShowMode(yl.SCENE_ROOMLIST)
	
		self:CheckNotic()
		self:getSocketNewMassge()
	end
	
	print("client加载完毕")

	
end
--通过移动按钮来隐藏收益按钮
function ClientScene:RefreshmoveBottomBtn()
	local ismoveIncomeBtn = false
	local city = self:getApp()._serverConfig.ip_name -- 当前客户端所在城市
	local lockcity = self:getApp()._serverConfig.lockcity -- 当前客户端所在城市
	
	
	

	if  (city and lockcity) then
		ismoveIncomeBtn = utils.checkIsLockCity( city,lockcity )
		if not ismoveIncomeBtn then
			local hadEnterGame = cc.UserDefault:getInstance():getBoolForKey("hadEnterGame",false)  --已经进过游戏
			if  (os.time() > self.firstEnterClientTime + 5*60 ) or hadEnterGame then
				ismoveIncomeBtn =  false	
			else
				ismoveIncomeBtn = true	
			end
		end
	elseif lockcity == nil then
		cc.UserDefault:getInstance():setBoolForKey("hadEnterGame",true)  --已经进过游戏
		ismoveIncomeBtn =  false	
	end
	--GlobalUserItem.onlyShowLand   1 表示需要隐藏 2表示
	GlobalUserItem.onlyShowLand = ismoveIncomeBtn
	
	local exchangeCount = self:getApp()._serverConfig.exchange or 0
	self.exchangeCount = exchangeCount  --充值多少金额的时候展示收益按钮
	local hasRechargeCount = cc.UserDefault:getInstance():getIntegerForKey("hasRechargeCount",0)

	if hasRechargeCount < exchangeCount then
		GlobalUserItem.safeChannle = true   --过审渠道
	else
		GlobalUserItem.safeChannle = false 
	end
	
	for k,v in ipairs(self.needMoveBtn) do
		if GlobalUserItem.safeChannle or ismoveIncomeBtn then
			v.btn:setPositionX(v.pos.x-BtnmoveX)
		else
			v.btn:setPositionX(v.pos.x)
		end
	end
end

function ClientScene:resetgameBroadcast()
	self.gamebroadcast = nil
end
function ClientScene:createLaba(parent)
	local itemNotice = self._notify:clone()
	itemNotice:ignoreContentAdaptWithSize(true) 
	itemNotice:loadTexture("public/gamelababg.png")
--	itemNotice:setContentSize(cc.size(700,17))
	local thumpetSize = itemNotice:getContentSize()
	local btn = itemNotice:getChildByName("btn_trumpet")
	btn:setTouchEnabled(false)
	local trumpetPX, trumpetPY = btn:getPosition()
	trumpetPX = trumpetPX-90
	btn:setPosition(trumpetPX,trumpetPY)
	
	local stencil  = display.newSprite()
	:setAnchorPoint(cc.p(0,0.5))
	stencil:setTextureRect(cc.rect(0,0,thumpetSize.width-100,thumpetSize.height))
	local _notifyClip = cc.ClippingNode:create(stencil)
	:setAnchorPoint(cc.p(0,0.5))
	_notifyClip:setInverted(false)
	_notifyClip:move(trumpetPX+10,trumpetPY-4)
	_notifyClip:addTo(itemNotice)
	local broadcast = Broadcast:create(parent,itemNotice)	
	broadcast:addTo(_notifyClip)
	self.gamebroadcast = broadcast
	self.gamebroadcast:setNoticeData({})
	ExternalFun.FixScaleUI(_notifyClip,true)
	return broadcast,itemNotice
end
function ClientScene:CheckNotic()
	local noticeMail_tab = {}
	local Mymail_tab = {}
	local bRedPoint = false
    local noticstr = cc.FileUtils:getInstance():getStringFromFile(device.writablePath .."noticeMail.txt")
	local mymailstr = cc.FileUtils:getInstance():getStringFromFile(device.writablePath .."myMail.txt")
	if noticstr ~= "" then
		noticeMail_tab = cjson.decode(noticstr)
	end
	if mymailstr ~= "" then
		Mymail_tab = cjson.decode(mymailstr)
	end
	for k,v in ipairs(noticeMail_tab) do
		if v.status == 0 then
				bRedPoint = true
			end
		end
	for k,v in ipairs(Mymail_tab) do
		if not v.status or v.status == 0 then
				bRedPoint = true
		end
	end
	self.msgRedPointSp:setVisible(bRedPoint)
end

function ClientScene:onBackgroundCallBack(bEnter)
	print("onBackgroundCallBack bEnter",bEnter,self.backgroundTs,os.time() - 300)
	appdf.clientSocket.lastPingAck = os.time()
	appdf.PostCustomEvent(yl.EVENT_CALL_BACKGROUND,{bEnter = bEnter},self)

	if not bEnter then
		self.backgroundTs = os.time()
	elseif self.backgroundTs and self.backgroundTs < os.time() - 300 then
		ExternalFun.httpNewVersion(self)
	end
end

function ClientScene:onGameCallBack(wMsgID,pData)
	print("ClientScene onGameCallBack:"..wMsgID,pData and pData.subid or nil)
	if wMsgID == protocol.SM_GAME_MESSAGE then
		if pData.subid == protocol.GM_SETTLE then
			if pData.playerid == GlobalUserItem.dwUserID then
				GlobalUserItem.lUserScore = pData.beforegold --+ pData.settlegold
				self:updateInfomation()
			end
		end
	end
	local curScene = self._sceneRecord[#self._sceneRecord]
	local bInGame = curScene == yl.SCENE_GAME
	--self:dismissPopWait()
	if 2 == code then   --cmdtable.lErrorCode == 2
		showToast(self,"金币不足",1)
		self:onKeyBack()
		performWithDelay(self, function () self:onChangeShowMode(yl.SCENE_SHOP) end,1)
			return
		end
end

function ClientScene:onEnterRoom()
	print("client onEnterRoom")

end

function ClientScene:onEnterTable()
	print("ClientScene onEnterTable", yl.inreconnectgame)
	local tag = self._sceneRecord[#self._sceneRecord]
	--getEnterGameInfo()
	if tag == yl.SCENE_GAME and not yl.inreconnectgame  then
		self._gameFrame:setViewFrame(self._sceneLayer:getChildByTag(yl.SCENE_GAME))
	else
		self:onChangeShowMode(yl.SCENE_GAME)
		yl.inreconnectgame = false
	end	
end

--启动游戏
function ClientScene:onStartGame()
	self.bJustLoginIn =  false
	ExternalFun.playClickEffect()
	self:showPopWait()
	self._gameFrame:onCheckCurGame()
	if self._popWait and self._popWait.loadingArm then
		self._popWait.loadingArm:makeAzhezhao()
	end
	-- self:showPopWait(nil,entergame.gameid or self.curgameid )
end

function ClientScene:onEnterGameScene( callback_ ,isingame)
	self.entergameCallback = callback_
	local app = self:getApp()
	local entergame = self:getEnterGameInfo()
	if entergame and not isingame and entergame.watch ~= 1  and  entergame.enterlimit and GlobalUserItem.lUserScore < entergame.enterlimit then
		self.queryLayer=QueryExit:create("当前房间进入需要"..(entergame.enterlimit/appdf.bili)..yl.UNIT.."，您金币不足，请充值？", function (bReTry)
			if bReTry == true then
				self:onChangeShowMode(yl.SCENE_SHOP)
			end
		end,true)
		:setCanTouchOutside(false)
		:addTo(self)
		return
	end
	if nil == entergame then
		-- showToast(self, "游戏信息获取失败", 3)
		return
	end
	if yl.updateList[self.curgameid] then
		showToast(self,"游戏正在更新",1)
		self:onKeyBack()
		return
	end
	GlobalUserItem.curRoomBaseScore = entergame.basescore or 0
	self.enterCallFun = function( result )
		if result and result == -1  then
			self:dismissPopWait()
			self:stopAction(self.delayPopWait)
			-- self:onKeyBack()
			return
		elseif result == 1 then
			self:dismissPopWait()
			self:stopAction(self.delayPopWait)
			return
		end
		self.inloadingRes = false
		if self.entergameCallback then
			self.entergameCallback()
		else
			self:onSendEnterGame()
		end
		
	end
	--查询是否还在其他游戏中
	self:showPopWait(nil,entergame.gameid or self.curgameid,true)
	self:onEnterTable()
	self.inloadingRes = true
	self:stopAction(self.delayPopWait)
	self.delayPopWait = performWithDelay(self,function( ... )
		if self._popWait and self._popWait.gameid and self._popWait.gameid > 0 then
			showToast(self,"进入游戏失败",2)
			local curScene = self._sceneRecord[#self._sceneRecord]
			if curScene then
				if curScene == yl.SCENE_GAME then
					self:onKeyBack()
				end
			end
			self:stopAction(self.delayPopWait)
		end
		self:dismissPopWait()
	end,self.curgameid == yl.buyu and 20 or 15)

end

function ClientScene:onSendEnterGame( bnotRest )
	local entergame = self:getEnterGameInfo()
	entergame.nEnterRoomIndex = GlobalUserItem.nCurRoomIndex
	if not bnotRest then
		self._gameFrame:onInitData()
	end
	self._gameFrame:setKindInfo(GlobalUserItem.nCurGameKind, GlobalUserItem.selectGameVersion)
	self._gameFrame:onEnterGame(entergame.gameid,entergame.roomid,entergame.tableid,entergame.srvid)
end



function ClientScene:onCleanPackage(name)
	if not name then
		return
	end
	for k ,v in pairs(package.loaded) do
		if k ~= nil then
			if type(k) == "string" then
				if string.find(k,name) ~= nil or string.find(k,name) ~= nil then
					print("package kill:"..k)
					package.loaded[k] = nil
				end
			end
		end
	end
end

function ClientScene:onLevelCallBack(result,msg)

end



--控制是退出还是返回 针对gamelistLayer isdisplay_back 是否弹出返回gamelistlayer主界面的按钮
function ClientScene:ShowgamelistLayerBack(isdisplay_back)
	self._btExit:setVisible(isdisplay_back)
	self._btExit:setEnabled(isdisplay_back)
	self:changeAreaTopsp(isdisplay_back)
	
end

function ClientScene:changeAreaTopsp(bchange)

	if bchange then
		self.freemoneybg:setVisible(false)
		self.rtuig_btn:setVisible(false)
		self.noticeBtn:setVisible(false)
		self:changegameNameSp(self.curgameid)
		self.gameNameSp:setVisible(true)
	--	self.gameNameSp:setTexture()
	else
		self.freemoneybg:setVisible(true)
		self.rtuig_btn:setVisible(true and  (not GlobalUserItem.onlyShowLand and not GlobalUserItem.safeChannle) )
		self.noticeBtn:setVisible(true and  (not GlobalUserItem.onlyShowLand and not GlobalUserItem.safeChannle) )
		self.gameNameSp:setVisible(false)
	end
	
end

function ClientScene:changegameNameSp(gameid)
	local spnameStr -- = string.format("GameList/gamename/game_%d_%d.png",gameid) 
	local gametype = GlobalUserItem.tb_gameType[tostring(gameid) ] or 1
	local tempstr = string.format("GameList/gamename/game_%d_%d.png",gameid,gametype) 
	if gametype > 1 and cc.FileUtils:getInstance():isFileExist(tempstr)  then
		
		spnameStr = tempstr
	else
		spnameStr = string.format("GameList/gamename/game_%d.png",gameid) 
	end
	
	local namesp = self.gameNameSp:getChildByName("gameNamesp")
	namesp:setTexture(spnameStr)
	local leftsp = self.gameNameSp:getChildByName("sp2")
	local rightsp = self.gameNameSp:getChildByName("sp3")
	local namespSize = namesp:getContentSize()
	local namespPosX ,namespPosY = namesp:getPosition()
	leftsp:setPositionX(namespPosX-namespSize.width*0.5-20)
	rightsp:setPositionX(namespPosX+namespSize.width*0.5+20)
	
	 local action = cc.CSLoader:createTimeline("plaza/nameNode.csb");
	action:setTimeSpeed(2)
    self.gameNameSp:runAction(action)
	action:gotoFrameAndPlay(0,90, false);
	
	
	
	self.curgameid = gameid
	
end
function ClientScene:onKeyBack()
	
	if not self.m_bEnableKeyBack then
		return
	end
		
		local curScene = self._sceneRecord[#self._sceneRecord]
		if curScene then
			if curScene == yl.SCENE_ROOM then
				self.bjl_tablels_info = {}
				-- self._gameFrame:onCloseSocket()
				
					self._LogonFrame:sendSocketData(protocol.CTRL_CLIENT_HALL,protocol.CM_EXITGAME)  --退出游戏房间  进入大厅
					-- self._LogonFrame:sendSocketData(protocol.CTRL_CLIENT_HALL,protocol.CM_GETGAMELIST)  -- 刷新大厅游戏列表
					self._gameFrame:onSelectGame(0)
					self:onChangeShowMode(yl.SCENE_ROOMLIST)
			

				return
			elseif curScene == yl.SCENE_GAME  then
				
				GlobalUserItem.nCurCGameId = nil
				if GlobalUserItem.bNoroomList or GlobalUserItem.onlyShowLand then
					self:onChangeShowMode(yl.SCENE_ROOMLIST)
				else
					self:onChangeShowMode(yl.SCENE_ROOM)
				end
				
				
				self:updateInfomation()
				GlobalUserItem.bNoroomList = false
				return
			end
		end
		self:onChangeShowMode()

end



function ClientScene:reloadClient()
	-- self:releasePublicRes()
	-- display.removeUnusedSpriteFrames()
	print("reloadClient重新加载client")
	self:getApp():enterSceneEx(appdf.CLIENT_SRC.."plaza.views.ClientScene","FADE",1)
	-- self:cachePublicRes()
end


function ClientScene:ExitClient()
	self._sceneLayer:setKeyboardEnabled(false)
	GlobalUserItem.nCurRoomIndex = -1
	self:updateEnterGameInfo(nil)
	self:getApp():enterSceneEx(appdf.CLIENT_SRC.."plaza.views.LogonScene","FADE",1)
end
local SUCCESS_CODE = 10000
--按钮事件
function ClientScene:onButtonClickedEvent(tag,ref)
	if tag == ClientScene.BT_EXIT then
		self:onKeyBack()
		ExternalFun.playClickEffect()
	elseif tag == ClientScene.BT_REGISTER then  --底部注册送金
		ExternalFun.playClickEffect()
		self:openBindingLayer(yl.SCENE_BINDING)
	elseif tag == ClientScene.BT_NOTIC then  --顶部公告按钮
		ExternalFun.playClickEffect()
		self.mail_bubble:setVisible(false)
		local today = os.date("%d", os.time())
		cc.UserDefault:getInstance():setIntegerForKey("mailBubbleDay",today)
		self:onChangeShowMode(yl.SCENE_GAMENOTICE)
        self.noticeBtn:getChildByName("bubble"):setVisible(false) --气泡
		_noticeLayer = self._sceneLayer:getChildByTag(yl.SCENE_GAMENOTICE)
	elseif tag == ClientScene.BT_RELIEF then  --领取救济金
		ExternalFun.playClickEffect()
		--[[cc.UserDefault:getInstance():setIntegerForKey("hasRechargeCount",1000)
		self:RefreshmoveBottomBtn()--]]
		
		self:openFreeGoldLayer()
	elseif tag == ClientScene.BT_RECHARGE then
		ExternalFun.playClickEffect()
		if not GlobalUserItem.ExchangeInfo and not appdf.isNullString(GlobalUserItem.URLconfig.exchangemethodurl)  then
			self:showPopWait()
			utils.getExchangeInfo({},function (recdata)
				self:dismissPopWait()
				GlobalUserItem.ExchangeInfo = recdata
				if recdata then
					self:onChangeShowMode(yl.SCENE_Recharge)
				else
					showToast(self,"获取收益信息失败",2)
				end
			end)
		else
			self:onChangeShowMode(yl.SCENE_Recharge)
		end
		
	elseif tag == ClientScene.BT_EXCHANGE then
		ExternalFun.playClickEffect()
			if GlobalUserItem.accounttype ~= 1 then
				showToast(self,"您当前账号是游客账号，为了您的资金安全，请您尽快绑定手机！",2)
			end
		self:onChangeShowMode(yl.SCENE_SHOP)

	elseif tag == ClientScene.BT_TRUMPET then
		ExternalFun.playClickEffect()
		self:getTrumpetSendLayer()
	elseif tag == ClientScene.BT_PERSON then

		ExternalFun.playClickEffect()
		self:onChangeShowMode(yl.SCENE_USERINFO)

	elseif tag == ClientScene.BT_KEFU then
		ExternalFun.playClickEffect()
		self:onChangeShowMode(yl.SCENE_KEFU)
	elseif tag == ClientScene.BT_BANK then
		ExternalFun.playClickEffect()
		self:onChangeShowMode(yl.SCENE_BANK)
	elseif tag == ClientScene.BT_Mail_Bubble then
		utils.playTipSound("sound/bubble.wav")
		ref:setVisible(false)
		local today = os.date("%d", os.time())
		cc.UserDefault:getInstance():setIntegerForKey("mailBubbleDay",today)
	elseif tag == ClientScene.BT_Kefu_Bubble then
		utils.playTipSound("sound/bubble.wav")
		local today = os.date("%d", os.time())
		cc.UserDefault:getInstance():setIntegerForKey("kefuBubbleDay",today)
		ref:setVisible(false)
		
	elseif tag == ClientScene.BT_TUIG then --推广按钮
		utils.playTipSound("sound/bubble.wav")
		self:onChangeShowMode(yl.SCENE_TUIGUAN)
	elseif tag == ClientScene.BT_bindIntru then
		self:openBindIntroduct()
	elseif tag == ClientScene.BT_bindIntru_ok then
		self.bind_tuijianrenID = self.bind_tuijian:getText()
		local function cb( data )
			if self.introductNode  then
				if data.code == SUCCESS_CODE then
					self.btn_bindIntrod:removeFromParent()
					self.introductNode:removeFromParent()
					
				else
					self.bind_tuijian:setText("")
				end
				showToast(self,data.msg or "绑定成功",1)
			end
			
		end
		utils.bindIntrodution( {invite_code=self.bind_tuijianrenID,user_id = GlobalUserItem.dwUserID},cb )
	end
	
end

function ClientScene:openBindIntroduct()
	local node = display.newNode()
	self.introductNode = node
	self:addChild(node)
	local lyaernode =  display.newLayer(cc.c4b(0, 0, 0, 180))
	local function onTouch(eventType, x, y)
        return true
    end
	lyaernode:setTouchEnabled(true)
	lyaernode:registerScriptTouchHandler(onTouch)
	node:addChild(lyaernode)
	local popnode = ExternalFun.loadCSB("popView/bindIntrodutionNode.csb", node )
	popnode:setPosition(display.cx,display.cy)
	ExternalFun.playOpenLayerAnimation(popnode)
	--popnode:getChildByName("Text_1"):setString(str)
	popnode:getChildByName("closebtn"):addTouchEventListener(function(ref,type) 
		if type == ccui.TouchEventType.ended then
			ref:setScale(1)
			node:removeFromParent()
			elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then
			ref:setScale(1)
		end
	end)
	local temptextfield = popnode:getChildByName("tempTextField")
	self.bind_tuijian = ccui.EditBox:create(temptextfield:getContentSize(),ccui.Scale9Sprite:create(""))
	--:setAnchorPoint(temptextfield:getPosit)
	:setPosition(temptextfield:getPosition())
	:setFontSize(40)
	:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC)
	:setMaxLength(15)
	:setPlaceHolder("请输入推荐人ID:")
	:addTo(temptextfield:getParent())
	
	temptextfield:removeFromParent()
	local okbtn = popnode:getChildByName("ok_btn")
	okbtn:setTag(ClientScene.BT_bindIntru_ok)
	okbtn:addTouchEventListener(self.btcallback)
	local function closecb( data )
		if data.code == SUCCESS_CODE then
			self.btn_bindIntrod:removeFromParent()
			self.introductNode:removeFromParent()
	
		end
	end
	if self.ChannelType == 2 then
		local bgetBindMoreByIp = cc.UserDefault:getInstance():getBoolForKey("getBindMoreByIp",false)
		MultiPlatform:getInstance():getClipboardData(function (data)
		--	local data = ""
		local pstart,pend = string.find(data,"weitjagent%-")
		
		if   pend then
		local str = string.sub(data,pend+1,string.len(data))
			if not appdf.isNullString( str ) then
		pstart,pend = string.find(str,"%.")
		if pend then
			str = string.sub(str,1,pend-1)
		end
			self.bind_tuijian:setText(str)
			self.bind_tuijianrenID = str
			self:onButtonClickedEvent(okbtn:getTag(),okbtn)
		elseif not bgetBindMoreByIp then
				utils.getBindMoreByIp( {bindtype = 2} ,closecb)
				cc.UserDefault:getInstance():setBoolForKey("getBindMoreByIp",true)
			end
				
		elseif not bgetBindMoreByIp then
				utils.getBindMoreByIp( {bindtype = 2},closecb )
				cc.UserDefault:getInstance():setBoolForKey("getBindMoreByIp",true)
				
		end
		end)
		
	end
end
function ClientScene:refreshLayer()
	local youkeicon = self._head:getChildByName("youkeicon")
	if GlobalUserItem.accounttype == 1 then 
		if youkeicon then
			youkeicon:removeFromParent()
		end
	else
		local youkeicon = display.newSprite("userinfo/youkeicon.png")
		youkeicon:setName("youkeicon")
		youkeicon:setScale(0.4)
		local size = self._head:getContentSize()
		youkeicon:setPosition(size.width-18,size.height-20)
		self._head:addChild(youkeicon,100)
	end
end


function ClientScene:onChangeShowMode(nTag, param,gameInfo)
	local tag = nTag
	local curtag 			--当前页面ID
	local bIn 				--进入判断
	yl.CUR_SCENE_TAG  = nTag
	--当前页面
	if #self._sceneRecord > 0 then
		curtag = self._sceneRecord[#self._sceneRecord]
	end
	ExternalFun.dismissTouchFilter()
	
	--退出判断
	if not tag then
		--返回登录
		if #self._sceneRecord < 2 then
			self:ExitClient()
			return
		end
		--清除记录
		local cur = self._sceneRecord[#self._sceneRecord]
		self._sceneRecord[#self._sceneRecord] = nil
		--上一页面
		tag = self._sceneRecord[#self._sceneRecord]
		--当前为游戏界面
		if cur == yl.SCENE_GAME then
			
			if tag ~= yl.SCENE_ROOM then --回退到房间桌子界面
				self._sceneRecord[#self._sceneRecord+1] = yl.SCENE_ROOM
				tag = yl.SCENE_ROOM
			end
			
			-- 玩法按钮
			if self:getChildByName(HELP_BTN_NAME) then
				self:removeChildByName(HELP_BTN_NAME)
			end
			-- 移除语音按钮
			if self:getChildByName(VOICE_BTN_NAME) then
				self:removeChildByName(VOICE_BTN_NAME)
			end
			-- 移除语音
			self:cancelVoiceRecord()
			if nil ~= self._gameFrame and type(self._gameFrame.clearVoiceQueue) == "function" then
				self._gameFrame:clearVoiceQueue()
			end
		end
	else
		--查找已有
		local oldIndex
		for i = 1 ,#self._sceneRecord do
			if self._sceneRecord[i] == tag then
				oldIndex = i
				break
			end
		end
		
		if not oldIndex then --新界面
			bIn = true --进入判断
			self._sceneRecord[#self._sceneRecord+1] = tag --记录ID
		else
			--重复过滤
			if oldIndex == #self._sceneRecord and not yl.inreconnectgame then
				return
			end
			
			--回退至已有记录
			for i = #self._sceneRecord,oldIndex+1 ,-1 do
				table.remove(self._sceneRecord, i)
			end
		end
	end
	--上一个页面
	self.m_nPreTag = self._sceneRecord[#self._sceneRecord]
	
	local this = self
	--当前页面
	if curtag then
		local cur_layer = self._sceneLayer:getChildByTag(curtag)
		if cur_layer then
			cur_layer:stopAllActions()
			--游戏界面不触发切换动画
			if tag == yl.SCENE_GAME or curtag == yl.SCENE_GAME then
				if curtag == yl.SCENE_SHOP then
					cur_layer:removeFromParent()
					self:onChangeShowMode(yl.SCENE_GAMELIST)
					return
				end
				cur_layer:removeFromParent()
				-- ExternalFun.closeWaitingTip()
				
				--ExternalFun.playPlazzBackgroudAudio()
			elseif tag == yl.SCENE_SHOP or curtag == yl.SCENE_OPTION or tag ==yl.SCENE_BINDING or  curtag == yl.SCENE_BINDING  then
				cur_layer:removeFromParent()
			elseif curtag == yl.SCENE_SHOP and tag ~= yl.SCENE_KEFU  then
				cur_layer:removeFromParent()
			else
				--动画判断
				local curAni
				if not bIn then
					curAni = cc.MoveTo:create(0.2,cc.p(yl.WIDTH,ExternalFun.getCenterFixY())) --退出动画
				else
					curAni = cc.MoveTo:create(0.2,cc.p(-yl.WIDTH,ExternalFun.getCenterFixY())) --返回动画
				end
				cur_layer:runAction(cc.Sequence:create(curAni,cc.RemoveSelf:create(true)))
			end
		end
	end
	
	--目标页面
	local dst_layer = self:getTagLayer(tag, param,gameInfo)
	self.dst_layer = dst_layer
	if dst_layer then
		--游戏界面不触发切换动画游戏界面不触发切换动画
		if tag == yl.SCENE_GAME then
			self._sceneLayer:setKeyboardEnabled(false)
			dst_layer:addTo(self._sceneLayer)

			performWithDelay(self,function( ... )
				this._sceneLayer:setKeyboardEnabled(true)
			end,0.1)
			cc.UserDefault:getInstance():setBoolForKey("hadEnterGame",true)  --已经进过游戏

		-- elseif  (tag == yl.SCENE_SHOP and curtag ~= yl.SCENE_KEFU)or (curtag == yl.SCENE_SHOP and tag ~= yl.SCENE_KEFU) or tag ==yl.SCENE_BINDING or  curtag == yl.SCENE_BINDING  then --or ( tag == yl.SCENE_ROOMLIST and curtag == nil )
		-- 	dst_layer:addTo(self._sceneLayer)
			-- dst_layer:stopAllActions()
			-- if dst_layer.onSceneAniFinish then
			-- 	dst_layer:onSceneAniFinish()
			-- end

		else
			--触摸过滤
			local movetime = 0.2
			if  tag == yl.SCENE_ROOMLIST and curtag == nil  and dst_layer.btnanimation then
				movetime = 0.2
		--		dst_layer:btnanimation()
			end
			ExternalFun.popupTouchFilter()
			self._sceneLayer:setKeyboardEnabled(false)
			if not bIn then
				dst_layer:move(-yl.WIDTH,ExternalFun.getCenterFixY())
			else
				dst_layer:move(yl.WIDTH,ExternalFun.getCenterFixY())
			end
			
			dst_layer:addTo(self._sceneLayer)
			dst_layer:stopAllActions()
			dst_layer:runAction(cc.Sequence:create(
			cc.MoveTo:create(movetime,cc.p(0,ExternalFun.getCenterFixY())),
			cc.CallFunc:create(function ()
				if dst_layer.onSceneAniFinish then
					dst_layer:onSceneAniFinish()
				end
				this._sceneLayer:setKeyboardEnabled(true)
				ExternalFun.dismissTouchFilter()
			end)
			)
			)
		end
	else
		print("dst_layer is nil")
		self:ExitClient()
		return
	end
	
	if tag == yl.SCENE_GAME then --or tag == yl.SCENE_ROOM then
		self._gameFrame:setViewFrame(dst_layer)
	end
	
	self._AreaBottom:stopAllActions()
	self._AreaTop:stopAllActions()
	if tag == yl.SCENE_GAMELIST or tag == yl.SCENE_ROOMLIST  or tag == yl.SCENE_ROOM  then
		if tag == yl.SCENE_ROOMLIST and not GlobalUserItem.onlyShowLand then
			self:reSetGameSearchPath(self.curgameid)
		end
		self._AreaTop:runAction(cc.MoveTo:create(0.2,cc.p(0,display.height)))
		
		local broomlist = tag == yl.SCENE_ROOMLIST
		if broomlist then
			self._AreaBottom:runAction(cc.MoveTo:create(0.2,cc.p(0,0)))
		else
			self._AreaBottom:runAction(cc.MoveTo:create(0.2,cc.p(0,-250)))
			
		end
		self._btPersonInfo:setVisible(broomlist)
		self:setLabaVisible(true)
		
		
		
	else
		
		
		if tag == yl.SCENE_GAME or tag ==yl.SCENE_BINDING then
			self._AreaBottom:setPosition(cc.p(0,-250))
			self._AreaTop:setPosition(cc.p(0,display.height+350+(display.height-750)))
			-- self.recharge:setVisible(false)
			self:setLabaVisible(false)
		else
			self._AreaBottom:runAction(cc.MoveTo:create(0.2,cc.p(0,-250)))
			self._AreaTop:runAction(cc.MoveTo:create(0.2,cc.p(0,display.height+350+(display.height-750))))

			self:setLabaVisible(false)
		end
		
	end
	local bRoomList = true
	local bEnableBackBtn = false
	
	bRoomList = (tag == yl.SCENE_ROOMLIST)
	
	if bRoomList then
		local var = true
		-- 单游戏
		self._btExit:setVisible(false)
		self:changeAreaTopsp(false)
		--self._btPersonInfo:setEnabled(var)
		if nil ~= self._head then
			--self._head:setVisible(not var)
		end
		self._bg:loadTexture("plaza/plazz/background.png")
		-- self._bg:loadTexture("Logon/roombg.png")
	elseif tag == yl.SCENE_ROOM then
		self._btExit:setVisible(true)
		self._btExit:setEnabled(true)
		self:changeAreaTopsp(true)
		-- showToast(self,"进入房间列表",2)
		-- self._btPersonInfo:setEnabled(true)
		if nil ~= self._head then
			self._head:setVisible(true)
		end
		self._bg:loadTexture("Logon/roombg.png")
	elseif tag == yl.SCENE_GAMELIST then
		self._btExit:setVisible(false)
		self._btExit:setEnabled(false)
		self:changeAreaTopsp(false)
		if nil ~= self._head then
			self._head:setVisible(true)
		end
		-- self._btPersonInfo:setEnabled(true)
		self._bg:loadTexture("plaza/plazz/background.png")
	elseif bEnableBackBtn then
		self._btExit:setVisible(true)
		self._btExit:setEnabled(true)
		self:changeAreaTopsp(true)
		-- self._btPersonInfo:setEnabled(false)
		
		if nil ~= self._head then
			self._head:setVisible(false)
		end
	else
		self._bg:loadTexture("Logon/roombg.png")
		-- ExternalFun.FixTopUI(self.dst_layer)
		-- self.dst_layer:setAnchorPoint(cc.p(0,1))
		-- self.dst_layer:setPositionY(display.height)
	end

	--self._bg:setVisible(false)
--	self._bg:setPositionY(-200)
	
	--更新金币
	infoShow = (tag == yl.SCENE_GAMELIST or tag == yl.SCENE_ROOMLIST or tag == yl.SCENE_ROOM or bRoomList)
	if true == infoShow then
		self:updateInfomation()
	end
	

	--游戏信息
	GlobalUserItem.bEnterGame = ( tag == yl.SCENE_GAME )
	if tag == yl.SCENE_ROOMLIST then
		GlobalUserItem.dwServerRule = 0
	end

	-- by djy 测试排除非windows平台判断
	if device.platform ~= "windows" and yl.SCENE_ROOMLIST == tag  and not GlobalUserItem.indownapk and (not self.checkapkts or (self.checkapkts < os.time() - 600 )) then
	-- if yl.SCENE_ROOMLIST == tag  and not GlobalUserItem.indownapk and (not self.checkapkts or (self.checkapkts < os.time() - 600 )) then
		-- 查看整包版本是否需要更新
		self.checkapkts = os.time()
		local cur_package_ver =  cc.UserDefault:getInstance():getStringForKey("package_ver") or ""
		if self:getApp()._serverConfig.apkversion and cur_package_ver ~= self:getApp()._serverConfig.apkversion then
			ExternalFun.httpNewVersion(self)
		end
	end
	
end
function ClientScene:openBindingLayer(tag,isTips)
	local layer =  Binding:create(self,isTips)
	layer:setTag(tag)
	self:addChild(layer,5)
	
end
--获取页面
function ClientScene:getTagLayer(tag, param,gameInfo)
	local dst
	if tag == yl.SCENE_GAMELIST  then
		-- dst =  GameListView:create(self,self:getApp()._gameList)
	elseif tag == yl.SCENE_ROOMLIST  then
		--是否有自定义房间列表
		self:RefreshmoveBottomBtn()	
		dst = RoomList:create(self, param,gameInfo)
		
		
	elseif tag == yl.SCENE_USERINFO then
		if appdf.APPSTORE_VERSION then
			UserInfo = appdf.req("UserInfoLayer_ios")
		end
		dst = UserInfo:create(self)
	elseif tag == yl.SCENE_KEFU then
		dst = KeFuLayer:create(self)
	elseif tag == yl.SCENE_GAMENOTICE then
		
		dst = NoticeLayer:create(self)
		
	elseif tag == yl.SCENE_TUIGUAN then
		dst = Agents:create(self)
	elseif tag == yl.SCENE_BANK then
		dst = Bank:create(self)
		
	elseif tag == yl.SCENE_ROOM then
		self._sceneLayer:removeChildByName("landnode")
		self.gameInfo = gameInfo or self.gameInfo
	
		local subgameSRCpath = appdf.gamecodepath.. self.gameInfo.gameid.. ".src.views.RoomView"
		local subgameRESpath = appdf.gamepath.. self.gameInfo.gameid.. "/src/views/RoomView.luac"
		local subgameRESpath2 = appdf.gamepath.. self.gameInfo.gameid.. "/src/views/RoomView.lua"
		
		if cc.FileUtils:getInstance():isFileExist(subgameRESpath) then
			local roomView = appdf.req(subgameSRCpath)
			dst =roomView:create(self,self.gameInfo)
		elseif cc.FileUtils:getInstance():isFileExist(subgameRESpath2) then
			local roomView = appdf.req(subgameSRCpath)
			dst =roomView:create(self,self.gameInfo)
		else
			dst = Room:create(self, param,self.gameInfo)
		end
		
	elseif tag == yl.SCENE_NOTICE then
		dst = Binding:create(self,true)
		
	elseif tag == yl.SCENE_Recharge then

		if  GlobalUserItem.accounttype == 1 then
			dst = ExchangeLayerNew:create(self)
		else
			dst = ExchangeLayerNew:create(self)
--			dst = Binding:create(self)		
		end
		
	elseif tag == yl.SCENE_GAME then
		local entergame = self:getEnterGameInfo()
		--self:showPopWait(nil,modulestr)
		if nil ~= entergame  then 
			-- self:addGameSearchpath()
			local modulestr = entergame.gameid or self.curgameid 

			for k,v in pairs(self._gameSearPathList) do
				if k ~= modulestr then
					self:reSetGameSearchPath(k)
				end
			end
			
			self:saveEnterCountWithRoomid(entergame.roomid)
		
			local gameScene = appdf.req(appdf.gamecodepath.. modulestr .. ".src.views.GameLayer") 
			
			local msgtype = type(gameScene)
			-- self._txtTips:setString("getTagLayer>>>>"..tostring(gameScene))
			if gameScene and ( msgtype == "userdata" or msgtype == "table" ) then
				dst = gameScene:create(self._gameFrame,self,self.enterCallFun)
			end
			self.retryTime = 0
		else
			
			showToast(self,"房间正在维护",4)

		end
		
	elseif tag == yl.SCENE_SHOP then
		if appdf.APPSTORE_VERSION then
			Shop = appdf.req("ShopLayer_ios")
		else
			
		end
		local cfg = self:getApp()._serverConfig
		dst = Shop:create(self, param,cfg)
	elseif tag == yl.SCENE_BINDING then
	
		dst = Binding:create(self)
	elseif tag == yl.SCENE_FRIEND then
		dst = Friend:create(self)
	end
	if dst then
		dst:setTag(tag)
	end
	if tag ~= yl.SCENE_GAME and not tolua.isnull(dst) then
		ExternalFun.FixCenterUI(dst)
	end
	
	return dst
end
function ClientScene:saveEnterCountWithRoomid(roomid)
	local enterRoomidInfo = {}
	local str = cc.FileUtils:getInstance():getStringFromFile(device.writablePath .."enterRoomidInfo.txt")
	if str ~= "" then
		enterRoomidInfo= cjson.decode(str)

	end

	local count = enterRoomidInfo[tostring(roomid)] or 0
	enterRoomidInfo[tostring(roomid)] = count + 1
	cc.FileUtils:getInstance():writeStringToFile(cjson.encode(enterRoomidInfo),device.writablePath .."enterRoomidInfo.txt")
			
end
	--显示等待
function ClientScene:showPopWait(delaytime,gameid,showSplash)
	if  self._popWait then
		self._popWait:removeFromParent()
	end

	print("showPopWait>>>>>>",delaytime,gameid)
		
	self._popWait = PopWait:create(isTransparent,gameid,showSplash)
	:show(self,"请稍候！")
	self._popWait:setLocalZOrder(yl.MAX_INT)	
	-- end
	self._popWait.type = 0 --bArm and 1 or 0
	self._popWait.gameid = gameid
	
	--定时删掉  避免卡死
	if self.sequence then
		self:stopAction(self.sequence)
	end
	if not gameid  or gameid < 1 then
		self.sequence = performWithDelay(self, function () self:dismissPopWait() end,delaytime or 6)
	end
end

--关闭等待
function ClientScene:dismissPopWait()
	local bfirstgame = cc.UserDefault:getInstance():getBoolForKey("firstGame",true)
	if bfirstgame then
		return
	end
	print(debug.traceback("dismissPopWait>>>>>>",2))
	self:stopAction(self.delayPopWait)
	if self.sequence then
		self:stopAction(self.sequence)
	end
	if self._popWait then
		if self._popWait.type == 1 then
			-- self._popWait:removeSelf()
	
			self._popWait = nil
			self.sequence = nil
		else
			self._popWait:dismiss()
			self._popWait = nil
			self.sequence = nil
		end
	end
end

--更新进入游戏记录
function ClientScene:updateEnterGameInfo( info )
	GlobalUserItem.m_tabEnterGame = info
end

function ClientScene:getEnterGameInfo(  )
	return GlobalUserItem.m_tabEnterGame
end

--获取游戏信息
function ClientScene:getGameInfo(wKindID)
	for k,v in pairs(self:getApp()._gameList) do
		if tonumber(v._KindID) == tonumber(wKindID) then
			return v
		end
	end
	return nil
end

--获取喇叭发送界面
function ClientScene:getTrumpetSendLayer()
	if nil == self.m_trumpetLayer then
		self.m_trumpetLayer = TrumpetSendLayer:create(self)
		self.m_plazaLayer:addChild(self.m_trumpetLayer)
	end
	self.m_trumpetLayer:showLayer(true)
end

function ClientScene:getSceneRecord(  )
	return self._sceneRecord
end
		
function ClientScene:updateInfomation(  )
			
	local str = ExternalFun.ChangeScore(GlobalUserItem.lUserScore or 0,2,",")

	if string.len(str) > 11 then
		str = string.sub(str, 1, 11) .. "..."
	end

	print("updateInfomation>>>>",str,GlobalUserItem.szNickName)
	self._gold:setString(str)

	self.nickNameText:setString(GlobalUserItem.szNickName)
	local _BankLayer = self._sceneLayer:getChildByTag(yl.SCENE_BANK)
	if _BankLayer then
		_BankLayer:refreshMoney()
	end
	--更新游戏内的金币
			
end
		
		--缓存公共资源
function ClientScene:cachePublicRes(  )
	cc.SpriteFrameCache:getInstance():addSpriteFrames("public/public.plist")
	local dict = cc.FileUtils:getInstance():getValueMapFromFile("public/public.plist")
	
	local framesDict = dict["frames"]
	if nil ~= framesDict and type(framesDict) == "table" then
		for k,v in pairs(framesDict) do
			local frame = cc.SpriteFrameCache:getInstance():getSpriteFrame(k)
			if nil ~= frame then
				frame:retain()
			end
		end
	end
	

	-- local tbArmaturename ={
	-- "Armature/CZDZ/CZDZ.ExportJson"}
	-- ExternalFun.addArmatureCache(tbArmaturename)
end

--释放公共资源
function ClientScene:releasePublicRes(  )
	
	
	pcall(function( ... )
		-- body
		ExternalFun:removeArmatureCache()
		cc.Director:getInstance():getTextureCache():removeUnusedTextures()
		cc.SpriteFrameCache:getInstance():removeUnusedSpriteFrames()
	end)
end

--输出日志
function ClientScene:logData(msg, addExtral)
	addExtral = addExtral or false
	local logtable = {}
	local entergame = self:getEnterGameInfo()
	if nil ~= entergame then
		logtable.name = entergame.name
		logtable.id = entergame.gameid
	end
	logtable.msg = msg
	local jsonStr = cjson.encode(logtable)
	LogAsset:getInstance():logData(jsonStr,true)
end

function ClientScene:addNotice(item)
	if nil == item then
		return
	end
	table.insert(self.m_tabInfoTips, 1, item)
	if not self.m_bNotifyRunning then
		self:onChangeNotify(self.m_tabInfoTips[self._tipIndex])
	end
end

function ClientScene:removeNoticeById(id)
	if nil == id then
		return
	end
	
	local idx = nil
	for k,v in pairs(self.m_tabInfoTips) do
		if nil ~= v.id and v.id == id then
			idx = k
			break
		end
	end
	
	if nil ~= idx then
		table.remove(self.m_tabInfoTips, idx)
	end
end

function ClientScene:getNoticeId()
	local tmp = self.m_nNotifyId
	self.m_nNotifyId = self.m_nNotifyId + 1
	return tmp
end
--设置游戏心跳
function ClientScene:checkHeartBreak()
	if device.platform == "android" then
		return
	end
	local curScene = self._sceneRecord[#self._sceneRecord]
	if self._gameFrame and curScene == yl.SCENE_GAME then
		if self._gameFrame._socket then
			self._gameFrame:QueryHeart()
		end
		self._gameFrame:onCheckHeartTime()
	end
end
--用于开始就展示斗地主
function ClientScene:addGame100Searchpath()
	self:addGameSearchpath(100)
end
function ClientScene:addGameSearchpath(gameid)
	local entergame = self:getEnterGameInfo()
	if nil ~= entergame or gameid then
		local modulestr = gameid or entergame.gameid
		self.curgameid = modulestr
		self._searchPath = appdf.gamepath .. modulestr .. "/res/"
		cc.FileUtils:getInstance():addSearchPath(self._searchPath,true)
		self._gameSearPathList[modulestr] = self._searchPath
	end
	local oldPaths = cc.FileUtils:getInstance():getSearchPaths()
	dump(oldPaths,"oldPaths>>>>")
end

function ClientScene:reSetGameSearchPath(gameid)

	local entergame = self:getEnterGameInfo()
		if nil ~= entergame or gameid or self.curgameid then
			local modulestr = gameid or self.curgameid or entergame.gameid 
			self._searchPath = appdf.gamepath .. modulestr .. "/res/"
			--重置搜索路径
			local oldPaths = cc.FileUtils:getInstance():getSearchPaths()
			local newPaths = {}
			for k,v in pairs(oldPaths) do
				if tostring(v) ~= tostring(self._searchPath) then
					table.insert(newPaths, v)
				end
			end
			cc.FileUtils:getInstance():setSearchPaths(newPaths)
			dump(newPaths,"newPaths>>>>")
			self:cleanPackageLoaded(modulestr)
			self._gameSearPathList[modulestr] = nil
		end
		-- self.curgameid = nil

end

function ClientScene:cleanPackageLoaded( kindid )
	for k ,v in pairs(package.loaded) do
		if k ~= nil then 
			if type(k) == "string" then
				if string.find(k,""..kindid) ~= nil then
					print("package kill:"..k) 
					package.loaded[k] = nil
				end
			end
		end
	end	
	display.removeUnusedSpriteFrames()
end

function ClientScene:exitTable( ... )
	local curScene = self._sceneRecord[#self._sceneRecord]
	if tag == yl.SCENE_GAME and self.dst_layer   then
		self.dst_layer :onExitTable()
	end
end

function ClientScene:enterGameinfo( gameinfo )
	self:addGameSearchpath(gameinfo.gameid)
	self:changegameNameSp(gameinfo.gameid)
	GlobalUserItem.nCurGameKind = gameinfo.gameid
	if  gameinfo.gameid == yl.baccaratnew or gameinfo.gameid == yl.baccaratnew_video or gameinfo.gameid == yl.longhudou or gameinfo.gameid == yl.balckred then --因为退出游戏也需要拉取 tablelist
		self.scene._gameFrame:onSelectGame(roomdata.gameid)
		self:onChangeShowMode(yl.SCENE_ROOM, self.m_bQuickStart,gameinfo )
		GlobalUserItem.bNoroomList = false
	elseif #gameinfo.roomls >= 2 then
		self._gameFrame:onSelectGame(gameinfo.gameid)
		self:onChangeShowMode(yl.SCENE_ROOM, self.m_bQuickStart,gameinfo )
		GlobalUserItem.bNoroomList = false
	else
		
		GlobalUserItem.nCurCGameId = gameinfo.roomls[1].roomid
		if gameinfo.roomls[1].status ~= 1 then
			showToast(self, "房间正在维护", 4)
			return
		end
		gameinfo.roomls[1].gameid = gameinfo.gameid
		local data = gameinfo.roomls[1]
		data.watch = data.watch or 0
		local lUserScore = GlobalUserItem.lUserScore or 0
		if data.watch == 0 and data.enterlimit > lUserScore then
			showToast(self._scene,"金币不足"..data.enterlimit/appdf.bili.."，请充值后重试")
			return
		elseif data.watch == 1 and data.enterlimit and data.enterlimit > lUserScore then

		end
	
		self:updateEnterGameInfo(gameinfo)
		self.m_bQuickStart = isQuickStart

		GlobalUserItem.nCurRoomIndex = gameinfo.level or 1
		GlobalUserItem.nCurGameKind = gameinfo.roomid
		self.retryTime = 0
		self:onStartGame()
		GlobalUserItem.bNoroomList = true
		
	end

	performWithDelay(self,function( ... )
		local areaTop = self.m_plazaLayer:getChildByName("top_bg")
		self._AreaTop = areaTop
		self._AreaTop:runAction(cc.MoveTo:create(0.2,cc.p(0,display.height)))
		ExternalFun.FixTopUI(areaTop)
		-- self._bg:setScale(display.sizeInPixels/750)
	end,0.1)
	
end
function ClientScene:getTuiguanVisible( )
	
	return not GlobalUserItem.onlyShowLand and not GlobalUserItem.safeChannle--self.rtuig_btn:isVisible()
end
--打开全民代理
function ClientScene:openAgents()
	self:onButtonClickedEvent(self.rtuig_btn:getTag(),self.rtuig_btn)
end

return ClientScene